﻿using HelloWorld.Entity;
using Microsoft.EntityFrameworkCore;

namespace HelloWorld.Config
{
    // 数据库上下文
    //System.ArgumentException:“'AddDbContext' was called with configuration, but the context type 'BloggingContext'
    //only declares a parameterless constructor.This means that the configuration passed to 'AddDbContext' will never be used.If configuration is passed to 'AddDbContext',
    //then 'BloggingContext' should declare a constructor that accepts a DbContextOptions<BloggingContext>
    //and must pass it to the base constructor for DbContext.”
    public class BloggingContext: DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        public BloggingContext(DbContextOptions<BloggingContext> options) : base(options)  // 调用父类的构造函数
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 单个索引
            modelBuilder.Entity<Post>()
                .HasIndex(p => p.BlogId)
                .HasDatabaseName("IX_BlogId");  // 指定索引名称

            // 联合索引
            modelBuilder.Entity<Post>()
                .HasIndex(e => new { e.Content, e.Title })
                .HasDatabaseName("IX_Content_Title");
        }
    }
}
